/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"CB291D47-D031-475A-9AD8-4835F217FF1B",variableType:4}
 */
var fmoneda = null;

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"19E420A9-C19E-4FEA-82ED-35EA2FE3A293"}
 */
function onAction_con(event) {
	if (globals.gMes == null || globals.gAnio == null || fmoneda == null)
	{
		globals.DIALOGS.showWarningDialog("Aviso","Datos mal ingresados verifique","Ok")
		return 						
	} 		
	var $columnas = new Array()
	var $codigos  = new Array()
	//Obtengo las divisiones y las guardo en un array para el nombre de las columnas
	/** @type {JSFoundSet<db:/contable/division>} */
	var $divisiones = databaseManager.getFoundSet('contable','division')
	$divisiones.loadAllRecords()
	var $cantDiv = databaseManager.getFoundSetCount($divisiones)
	for (var i = 1 ; i <= $cantDiv ; i++)
	{
		$divisiones.setSelectedIndex(i)
		$columnas[i+1] = $divisiones.abreviatura
		$codigos[i+1]  = $divisiones.codigo
	}
	$columnas[0] = 'Numero de Cuenta'
	$columnas[1] = 'Cuenta'

	var $ds = databaseManager.createEmptyDataSet(0,$columnas)
	var $mon
	if (fmoneda == 1)
		$mon = 'Pesos'
	else
		$mon = 'Dolares'
	var $linea = new Array('Fecha: '+globals.gMes+'-'+globals.gAnio,'Moneda: '+$mon)
	for (var j = 2 ; j <= $cantDiv+1 ; j++)
	{
		$linea[j] = ''
	}
	$ds.addRow(1,$linea)
	$ds.addRow(2,$columnas)
	
	var query = 'select cuentas_id,division,cuenta_nueva,debe_pes,debe_dol,haber_pes,haber_dol,anio,mes from saldos INNER JOIN cuentas ON saldos.cuentas_id = cuentas.cuenta_id '  
	var args = new Array()
	args[0] = globals.gUservID
	args[2] = globals.gAnio
	args[3] = globals.gUservID
	args[5] = globals.gAnio
	args[6] = globals.gMes
	query += 'where empresa = ? and anio < ? or empresa = ? and anio = ? and mes <= ?'
	query += ' order by cuentas_id,division'
	var max = -1
	var ds_saldos = databaseManager.getDataSetByQuery('contable',query,args,max)
	var ctos = ds_saldos.getMaxRowIndex()
	if (ctos == 0)
	{
		globals.DIALOGS.showWarningDialog("Aviso","Sin movimientos","Ok")
		return 				
	}
	var nCuentas_id   = ds_saldos.getColumnNames().indexOf("cuentas_id",0)     +1
	var nDivision     = ds_saldos.getColumnNames().indexOf("division",0)       +1	
	var nCuenta_nueva = ds_saldos.getColumnNames().indexOf("cuenta_nueva",0)   +1
	var nDebe_pes     = ds_saldos.getColumnNames().indexOf("debe_pes",0)       +1
	var nDebe_dol     = ds_saldos.getColumnNames().indexOf("debe_dol",0)       +1
	var nHaber_pes    = ds_saldos.getColumnNames().indexOf("haber_pes",0)      +1
	var nHaber_dol    = ds_saldos.getColumnNames().indexOf("haber_dol",0)      +1
	//var nAnio         = ds_saldos.getColumnNames().indexOf("anio",0)           +1
	//var nMes          = ds_saldos.getColumnNames().indexOf("mes",0)            +1
	
	var $cuenta   = ds_saldos.getValue(1,nCuentas_id)
	var $division = ds_saldos.getValue(1,nDivision)	
	var $auxil    = ds_saldos.getValue(1,nCuenta_nueva)
	var $formato  = $auxil.substring(0, 11);
	var $texto    = $auxil.substring(12);
    $texto = utils.stringTrim($texto);
	var $linea = new Array()
	$linea[0] = $formato
	$linea[1] = $texto
	for (var j = 2 ; j <= $cantDiv+1 ; j++)
	{
		$linea[j] = 0
	}	

    var $cols = new Array('cuenta','descripcion','division','saldo_pesos','saldo_dolar')
    var ds_balance = databaseManager.createEmptyDataSet(0,$cols)
	var saldo_pes = 0
	var saldo_dol = 0
	var $reg = new Array()
	for (var i = 1 ; i <= ctos ; i++)
	{
		ds_saldos.rowIndex = i
		if ($cuenta != ds_saldos.getValue(i,nCuentas_id))
		{
			if (saldo_pes != 0 && saldo_dol != 0)
			{
				$reg = new Array($formato,$texto,$division,saldo_pes,saldo_dol)
	    		ds_balance.addRow($reg)
	    		if (fmoneda == 1)
	    		{
					$linea[$codigos.indexOf($division,0)] = utils.numberFormat(saldo_pes,'0.00')
				}
				else
	    		{
					$linea[$codigos.indexOf($division,0)] = utils.numberFormat(saldo_dol,'0.00')
				} 
    		}
    		else
			{
    			$reg = new Array($formato,$texto,$division,null,null)
	    		ds_balance.addRow($reg)
			}
			$ds.addRow($linea)
			$linea = new Array()
			for (var j = 2 ; j <= $cantDiv+2 ; j++)
			{
				$linea[j] = 0
			}
			var $auxil   = ds_saldos.getValue(i,nCuenta_nueva)	
			var $formato = $auxil.substring(0, 11);
			var $texto = $auxil.substring(12);
			$texto = utils.stringTrim($texto);
			$linea[0] = $formato
			$linea[1] = $texto 
			$cuenta   = ds_saldos.getValue(i,nCuentas_id)
	 		$division = ds_saldos.getValue(i,nDivision)
			saldo_pes = ds_saldos.getValue(i,nDebe_pes) - ds_saldos.getValue(i,nHaber_pes) 
	        saldo_dol = ds_saldos.getValue(i,nDebe_dol) - ds_saldos.getValue(i,nHaber_dol) 		
		}
		else
		{
			if ($division == ds_saldos.getValue(i,nDivision))
			{
				saldo_pes = saldo_pes +	ds_saldos.getValue(i,nDebe_pes) - ds_saldos.getValue(i,nHaber_pes) 
		        saldo_dol = saldo_dol +	ds_saldos.getValue(i,nDebe_dol) - ds_saldos.getValue(i,nHaber_dol) 
			}
			else
			{
				if (saldo_pes != 0 && saldo_dol != 0)
				{
					var $reg = new Array($formato,$texto,$division,saldo_pes,saldo_dol)
		    		ds_balance.addRow($reg)
		    		if (fmoneda == 1)
		    		{
						$linea[$codigos.indexOf($division,0)] = utils.numberFormat(saldo_pes,'0.00')
					}
					else
		    		{
						$linea[$codigos.indexOf($division,0)] = utils.numberFormat(saldo_dol,'0.00')
					} 						
	    		}
	    		else
				{
	    			var $reg = new Array($formato,$texto,$division,null,null)
		    		ds_balance.addRow($reg)
				}
		 		$division = ds_saldos.getValue(i,nDivision)
				saldo_pes = ds_saldos.getValue(i,nDebe_pes) - ds_saldos.getValue(i,nHaber_pes) 
		        saldo_dol = ds_saldos.getValue(i,nDebe_dol) - ds_saldos.getValue(i,nHaber_dol) 		
			} 		
		}
	}
	if (saldo_pes != 0 && saldo_dol != 0)
	{
		$reg = new Array($formato,$texto,$division,saldo_pes,saldo_dol)
		ds_balance.addRow($reg)
		if (fmoneda == 1)
		{
			$linea[$codigos.indexOf($division,0)] = utils.numberFormat(saldo_pes,'0.00')
		}
		else
		{
			$linea[$codigos.indexOf($division,0)] = utils.numberFormat(saldo_dol,'0.00')
		} 
	}
	else
	{
		$reg = new Array($formato,$texto,$division,null,null)
	    ds_balance.addRow($reg)
	}
	$ds.addRow($linea)
	
	var frm = solutionModel.getForm('saldiv_tab')
	var $tipos = new Array(JSColumn.TEXT,JSColumn.TEXT,JSColumn.INTEGER,JSColumn.NUMBER,JSColumn.NUMBER)
	var dSource = ds_balance.createDataSource('saldos',$tipos)
	frm.dataSource = dSource
	forms.saldiv_tab.controller.sort("cuenta asc")
	forms.saldiv_tab.controller.recreateUI()
	
	elements.tabs_220.removeAllTabs()
	elements.tabs_220.addTab(forms.saldiv_tab)  

 /*	var fw = new Packages.java.io.FileWriter('c:/datos/saldos.csv');
	var bw = new Packages.java.io.BufferedWriter(fw);
	$ds.sort(3,true)
	var $csv = $ds.getAsText(';','\n','"',false)	
	bw.write($csv,0,$csv.length)
	
	bw.close()
	fw.close()
	application.showURL('file:///c:/datos/saldos.csv')*/
}

/**
 * Callback method for when form is shown.
 *
 * @param {Boolean} firstShow form is shown first time after load
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"5004DC52-03CC-4E3A-8E94-5F8CAF7341D6"}
 * @AllowToRunInFind
 */
function onShow(firstShow, event) {
	controller.loadRecords(null)
}

/**
 * Handle changed data.
 *
 * @param {String} oldValue old value
 * @param {String} newValue new value
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"9E9AA975-C352-4E13-B359-3B15173956CA"}
 */
function onDataChangeFecha(oldValue, newValue, event) {
	globals.gMes 	= newValue.substring(0,newValue.indexOf('|'))
	globals.gAnio	= newValue.substring(newValue.indexOf('|')+1,newValue.length)
	return true
}
